Class Nur.MNISV3.Service.Session Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取院区     
ClassMethod GetLocHospID(locID = "") As %String
{
    n (locID)
    i (locID="") q ""
    q $p($g(^CTLOC(locID)),"^",22)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取科室   
ClassMethod GetWardLocID(wardID = "") As %String
{
    n (wardID)
    i (wardID="") q ""
    q $p($g(^PAWARD(wardID)),"^",5)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取院区     
ClassMethod GetWardHospID(wardID = "") As %String
{
    n (wardID)
    i (wardID="") q ""
    s wardLocID=$p($g(^PAWARD(wardID)),"^",5)
    q ..GetLocHospID(wardLocID)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取科室 
ClassMethod GetPatLocID(admID = "") As %String
{
    n (admID)
    i (admID="") q ""
    s patWardLocID=""
    s patWardID=$p($g(^PAADM(admID)),"^",70)
    i (patWardID'="") s patWardLocID=$p($g(^PAWARD(patWardID)),"^",5)
    i (patWardLocID'="") q patWardLocID
    s patLocID=$p($g(^PAADM(admID)),"^",4)
    q patLocID
}

ClassMethod GetPatWardID(admID = "") As %String
{
    n (admID)
    i (admID="") q ""
    s patWardID=$p($g(^PAADM(admID)),"^",70)
    q patWardID
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取院区  
ClassMethod GetPatHospID(admID = "") As %String
{
    n (admID)
    i (admID="") q ""
    s patWardLocID=""
    s patWardID=$p($g(^PAADM(admID)),"^",70)
    i (patWardID'="") s patWardLocID=$p($g(^PAWARD(patWardID)),"^",5)
    i (patWardLocID'="") q ..GetLocHospID(patWardLocID)
    s patLocID=$p($g(^PAADM(admID)),"^",4)
    q ..GetLocHospID(patLocID)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取科室     
ClassMethod GetOrdLocID(oeoreId = "") As %String
{
    n (oeoreId)
    s oeoreId=$replace(oeoreId,"-","||")
    s oew=+oeoreId,chl=$p(oeoreId,"||",2)
    i (chl="") q ""
    s admID=+$g(^OEORD(oew))
    q ..GetPatLocID(admID)
}

ClassMethod GetOrdWardID(oeoreId = "") As %String
{
    n (oeoreId)
    s oeoreId=$replace(oeoreId,"-","||")
    s oew=+oeoreId,chl=$p(oeoreId,"||",2)
    i (chl="") q ""
    s admID=+$g(^OEORD(oew))
    q ..GetPatWardID(admID)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取院区     
ClassMethod GetOrdHospID(oeoreId = "") As %String
{
    n (oeoreId)
    s oeoreId=$replace(oeoreId,"-","||")
    s oew=+oeoreId,chl=$p(oeoreId,"||",2)
    i (chl="") q ""
    s admID=+$g(^OEORD(oew))
    q ..GetPatHospID(admID)
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   取院区   
/// Other:         设置按当前院区，业务按默认院区
ClassMethod GetMainHospID(hospID = "") As %String
{
    n (hospID)
    i (hospID="") q ""
    i '(##class(%Dictionary.MethodDefinition).%ExistsId("web.DHCBL.BDP.BDPMappingHOSP||GetDefHospIdByTableName")) q hospID
    q ##class(web.DHCBL.BDP.BDPMappingHOSP).GetDefHospIdByTableName(##class(Nur.HISUI.MNIS.Config).#MAINTABLE,hospID,$zd(+$h,3))
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:    w ##class(Nur.MNISV3.Service.Session).GetECPIP()
ClassMethod GetECPIP(hospID = "") As %String
{
    n (hospID)
    s ecpIP=##class(ext.util.String).ServerIP()
    i (ecpIP'="")&&($d(^DHCIntranetMapping(ecpIP))) d
    .s ecpIP=$g(^DHCIntranetMapping(ecpIP))
    q ecpIP
}

/// Creator：      EH
/// CreatDate：    2021-06-18      
ClassMethod GetFTPIP(hospID = "") As %String
{
    n (hospID)
    s ftpIP=##class(NurMp.Service.Image.Ftp).getFtpInfo(hospID).GetAt("ftpIp")
    i (ftpIP'="")&&($d(^DHCIntranetMapping(ftpIP))) d
    .s ftpIP=$g(^DHCIntranetMapping(ftpIP))
    q ftpIP
}

/// Creator：      EH
/// CreatDate：    2021-06-18
/// Description:   初始化session
/// Other:         经测试每次Soap请求都会生成一个session，并且每次的id不同，这个方法仅用于PDA的Soap方法初始化session.Data，不做登录判断
ClassMethod InitSessionData(logonInfo) As %Status
{
    n (logonInfo,%request,%session)
    s ^MML("InitSessionData")=$lb(logonInfo)
    s $zt="InitSessionDataZT"
    i ('$isobject(logonInfo)) s logonObj=##class(Nur.JSON).Decode(logonInfo)
    e  s logonObj=logonInfo
    s userId=logonObj.GetAt("userId")
    s wardId=logonObj.GetAt("wardId")
    s hospId=logonObj.GetAt("hospitalId")
    s groupId=logonObj.GetAt("groupId")
    s locId=logonObj.GetAt("locId")
    i ('$d(%request))!('$d(%session)) q "-1^Soap session不存在"
    s hospDesc=""
    i (hospId'="") s hospDesc=$p($g(^CT("HOSP",hospId)),"^",2)
    s (locAlis,locDesc)=""
    i (locId'="") d
    .s locDesc=$p($g(^CTLOC(locId)),"^",2)
    .i (locDesc["-") d
    ..s locAlis=$p(locDesc,"-",1)
    ..s locDesc=$p(locDesc,"-",2)
    i (userId'="") d
    .s userCode=$p($g(^SSU("SSUSR",userId)),"^",1)
    .s passWord=$p($g(^SSU("SSUSR",userId)),"^",3)
    .i (##class(%Dictionary.CompiledMethod).%ExistsId("web.SSUser||IsValidUserMd5Password")) d
    ..s passWord=##class(web.Util.Encryption).MD5HexStr(passWord)
    s groupDesc=""
    i (groupId'="") s groupDesc=$p($g(^SSU("SSGRP",groupId)),"^",1)
    s %request.Data("USERNAME",1)=$g(userCode)
    s %request.Data("PASSWORD",1)=$g(passWord)
    s %request.Data("Hospital",1)=$g(hospDesc)
    s %request.Data("DEPARTMENTAlias",1)=$g(locAlis)
    s %request.Data("DEPARTMENT",1)=$g(locDesc)
    s %request.Data("SSUSERGROUPDESC",1)=$g(groupDesc)
    /// 初始化session
    k %session.Data
    s %session.Data("LogonAttempts")=""
    s %session.Data("PreviousUser")=""
    s %session.Data("LOGON.WARDID")=$g(wardId)
    s %session.Data("LOGON.CTLOCID")=$g(locId)
    s %session.Data("LOGON.SITECODE")=""
    s %session.Data("LOGON.USERID")=$g(userId)
    s %session.Data("LOGON.USERCODE")=$g(userCode)
    s %session.Data("LOGON.USERNAME")=""
    s %session.Data("LOGON.GROUPID")=$g(groupId)
    s %session.Data("LOGON.GROUPDESC")=$g(groupDesc)
    s %session.Data("LOGON.LANGID")=""
    s %session.Data("LOGON.GROUPMENUS")=""
    s %session.Data("LOGON.LAYOUTMANAGER")=""
    s %session.Data("LOGON.ALLOWLAYOUTMANAGER")=""
    s %session.Data("LOGON.ALLOWCOLUMNMANAGER")=""
    s %session.Data("LOGON.PPMCAPTURE")=""
    s %session.Data("LOGON.PPMDISPLAY")=""
    s %session.Data("LOGON.ROUND")=""
    s %session.Data("LOGON.ROUNDDESC")=""
    s %session.Data("LOGON.HOSPID")=$g(hospId)
    s %session.Data("LOGON.HOSPDESC")=$g(hospDesc)
    s %session.Data("LOGON.TRUSTID")=""
    s %session.Data("LOGON.TRUSTDESC")=""
    s %session.Data("LOGON.SSUSERLOGINID")=""
    s %session.Data("TITLE")=""
    s %session.Data("LOGON.TIMEOUT")="900"
    s %session.Data("REMOTE_ADDR")=%request.GetCgiEnv("REMOTE_ADDR")
    s %session.Data("COMPUTER_NAME")=%request.GetCgiEnv("REMOTE_ADDR")
    s %session.Data("SERVER_NAME")=%request.GetCgiEnv("SERVER_NAME")
    s %session.Data("LOGON.REGION")=""
    s %session.Data("LICENSE.TC")=""
    s %session.Data("SYS.LANGID")=""
    s %session.Data("SYS.TIMEOUT")=""
    s %session.Data("LOGON.ADUSERNAME")=""
    s %session.Data("LOGON.ADPASSWORD")=""
    s %session.Data("ContainerPin")=""
    s %session.Data("ContainerName")=""
    s %session.Data("CASUSERNAME")=""
    /// 设置参数
    s STATUS=""
    s mystatus=1
    s ValidUser=0
    s logonround=0
    s roundok=1
    s overrideauth=0
    s readonly=""
    s config=##class(websys.Configuration).%OpenId(1,0)
    i ($isobject(config)) {
        s %session.Data("LOGON.SITECODE")=config.SiteCode
        s %session.Data("LOGON.LAYOUTMANAGER")=config.LayoutManager
        s %session.Data("LOGON.TIMEOUT")=%session.AppTimeout
        s %session.Data("LOGON.PPMDISPLAY")=config.PerformanceStatisticsDisplay
        s %session.Data("LOGON.PPMCAPTURE")=config.PerformanceStatisticsCapture
        s %session.Data("LOGON.LANGID")=config.LanguageApp
        i (config.LanguageApp="") s %session.Data("LOGON.LANGID")=$o(^SS("LAN",0))
        s overrideauth=config.OverrideAuthentication
        d config.%Close()
        s %session.Data("TITLE")=$p($g(^CF("SM",1)),"^",5)
        s %session.Data("LICSITE")=$p($g(^CF("SM",1)),"^",43)
    }
    i ($g(%request.Data("RELOGON",1))'="") s STATUS="SESSION_EXPIRED"
    i ('overrideauth) {
        s username=$g(%request.Data("USERNAME",1))
        s password=$g(%request.Data("PASSWORD",1))
        s department=$g(%request.Data("DEPARTMENT",1))
        s departmentAlias=$g(%request.Data("DEPARTMENTAlias",1))
        s hosp=$g(%request.Data("Hospital",1))
        i (department'="")&(departmentAlias'="") d
        .i (department'["-") s department=departmentAlias_"-"_department
        s round=$g(%request.Data("ROUND",1))
    } else {
        ; in this case always use this and never use the value from request.Data
        s username=%request.GetCgiEnv("REMOTE_USER")
        ; get the username part only in case if is prefixed with domain
        s username=$p(username,"\",$l(username,"\"))
        s password="*****"
        s department=""
        s departmentAlias=""
        s hosp=""
        s round=""
        s readonly="READONLY"
    }
    s ip=$g(%request.Data("IPAddress",1),%request.CgiEnvs("REMOTE_ADDR"))
    s hostName=%request.Get("DNSHostName")
    s macAddr=%request.Get("MACAddr")
    ; remove any old error messages
    d ##class(websys.Message).%DeleteId(%session.SessionId)
    ; remove any (and all) existing session data
    s Computer=%session.Data("REMOTE_ADDR")
    d ##class(websys.Lock).LockClearComputer(Computer)
    /// 登录
    i ($g(username)'="")&($g(password)'="") {
        ; return -ve rowid if valid user but not active !
        i (##class(%Dictionary.CompiledMethod).%ExistsId("web.SSUser||IsValidUserMd5Password")) {
            i ('overrideauth) {
                s userid=##class(web.SSUser).IsValidUserMd5Password(username,password)
            } else {
                s userid=##class(web.SSUser).IsValidUserMd5Password(username,password,1)
            }
        } else {
            i ('overrideauth) {
                s userid=##class(web.SSUser).IsValidUser(username,password)
            } else {
                s userid=##class(web.SSUser).IsValidUser(username,password,1)
            }
        }
        i (userid>0) s ValidUser=1
        e  s userid=##class(web.SSUser).GetIdFromCodeOrDescription(username)
        i (ValidUser) {
            s logonround=1
            s grpid=$g(%session.Data("LOGON.GROUPID"))
            s grpdes=$g(%request.Data("SSUSERGROUPDESC",1))
            i (grpdes'="") s grpid=##class(web.SSGroup).GetIdFromCodeOrDescription(grpdes)
            d ##class(web.SSUser).SetUserSessionData(userid,$g(grpid))
            ; overwrite system config for application timeout
            d ##class(epr.GroupSettings).SetGroupSessionTimeout(grpid)
            s locid=##class(web.SSUserOtherLogonLoc).CheckLoginLocation(department,hosp)
            i ('##class(web.SSUserOtherLogonLoc).IsValidGroupLocation(userid,$g(grpid),locid,0)) s locid="",department=""
            ;s roundid=##class(web.CTCareProv).GetIdFromCodeOrDescription(round)
            s roundid=""
            i (roundid="") {
                i (round'="") s STATUS="ROUND_CAREPROV",roundok=0
            } else {
                s %session.Data("LOGON.ROUND")=roundid      
                s %session.Data("LOGON.ROUNDDESC")=round
            }
            i (overrideauth) s locid=##class(web.CTLoc).GetIdFromCodeOrDescription(department)
            i (roundok)&(locid'="") {
                s wardid=$o(^PAWARD(0,"WARD_LocationDR",locid,""))
                i (wardid'="") {
                    s ctcpt=$p($g(^SSU("SSUSR",userid)),"^",14)
                    i ($g(ctcpt)'="") {
                        s typid=$p($g(^CTPCP(ctcpt,1)),"^",4)
                        i ($g(typid)'="") {
                            s typdes=$p($g(^CT("CPT",typid)),"^",4)
                            i ($g(typdes)="NURSE") s %session.Data("LOGON.WARDID")=wardid
                        }
                    }
                }
                ;s %session.Data("LOGON.CTLOCID")=locid
                ;s %session.Data("LOGON.CTLOCDESC")=department
                s hospid=$p($g(^CTLOC(+locid)),"^",22),%session.Data("LOGON.HOSPID")=hospid
                s hospdesc=$p($g(^CT("HOSP",+hospid)),"^",2),%session.Data("LOGON.HOSPDESC")=hospdesc
                s trustid=##class(web.CTHospital).getTrustId(hospid),%session.Data("LOGON.TRUSTID")=trustid
                s trustdesc=$p($g(^PAC("TRUST",+trustid)),"^",2),%session.Data("LOGON.TRUSTDESC")=trustdesc
            }
        }
    }
    ; fetch translations at end to make sure %session("LOGON.LANGID") has been s correctly
    d ##class(websys.Component).GetComponentMessages(.t,"websys.SYSTEM,SSUserLogon")
    s %session.Data("XMONTHSSHORT")=$g(t("XMONTHSSHORT"),"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")
    i (STATUS'="") s STATUS=$g(t(STATUS))
    i ($d(%response)) {
        i (%response.ServerSideRedirect'="") q 0
    }
    i (mystatus) {
        s %session.Data("initStatus")=2
    }
    q mystatus
InitSessionDataZT
    q "-1^"_$ze
}

/// Description:  开启session
/// Other:        d ##class(Nur.MOES.Service.Session).OpenSession("20665","101")
ClassMethod OpenSession(userID = "", locID = "", name = "") As %Status
{
    n (userID,locID,name,%session)
    s status=0
    i (name="") s name="debug"_$j
    s (wardID,hospID)=""
    i (locID'="") d
    .s wardID=$o(^PAWARD(0,"WARD_LocationDR",locID,""))
    .s hospID=$p($g(^CTLOC(locID)),"^",22)
    i ('$d(%session)) d
    .s %session=##class(%CSP.Session).%New(name)
    .d %session.Unlock()
    .s %session.Data("LOGON.HOSPID")=hospID
    .s %session.Data("LOGON.CTLOCID")=locID
    .s %session.Data("LOGON.WARDID")=wardID
    .s %session.Data("LOGON.GROUPDESC")="住院护士长"
    .s %session.Data("LOGON.USERID")=userID
    .s status=1
    q status
}

/// Description:  关闭session
/// Other:        d ##class(Nur.MOES.Service.Session).CloseSession()
ClassMethod CloseSession(name = "") As %Status
{
    n (name,%session)
    s status=0
    i (name="") s name="debug"_$j
    i ($d(%session))&&(%session.SessionId=name) d
    .s %session.EndSession=1
    .d %session.%Close()
    .d %session.%Delete()
    .k %session
    .s status=1
    q status
}

}
